<?php
/*
 * @Author: lokei
 * @Date: 2022-09-19 13:45:10
 * @LastEditors: lokei
 * @LastEditTime: 2022-12-05 09:21:00
 * @Description: 
 */

namespace App\Http\Controllers\Cms\Qrcode;

use App\Common\Miniapp\Common;
use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Cms\Qrcode\QrcodeModel;
use Illuminate\Http\Request;

class QrcodeController extends Controller
{
	public function get(Request $request)
	{
		$qrcode = QrcodeModel::where('id', '=', $request->input('id'))->first();
		$res = ResultTool::success();
		$res['data'] = $qrcode;
		return $res;
	}

	public function getOrCreate(Request $request) {
		$qrcode = QrcodeModel::where('type', '=', 'miniapp')->where('page', '=', $request->input('page'))->where('scene', '=', $request->input('scene'))->first();
		if (is_null($qrcode)) {
			$qrcode = $this->generate($request->all());
		}
		$res = ResultTool::success();
		$res['data'] = $qrcode;
		return $res;
	}

	public function getOrCreateOfMe(Request $request) {
		$user = app('auth')->user();
		$scene = 'uid=' . $user->uid;
		$qrcode = QrcodeModel::where('type', '=', 'miniapp')->where('scene', '=', $scene)->first();
		if (is_null($qrcode)) {
			$qrcode = $this->generate( array_merge($request->all(), [
				'scene' => $scene,
				'name' => '分销二维码：' . $user->uid
			]));
		}
		$res = ResultTool::success();
		$res['data'] = $qrcode;
		return $res;
	}

	public function list(Request $request)
	{
		$items = QrcodeModel::where('mode', '=', $request->input('mode'))->get();
		$data['items'] = $items;
		$data['count'] = count($items);
		$res = ResultTool::success();
		$res['data'] = $data;
		return $res;
	}

	public function create(Request $request)
	{
		$qrcode = QrcodeModel::where('type', '=', 'miniapp')->where('page', '=', $request->input('page'))->where('scene', '=', $request->input('scene'))->first();
		if (is_null($qrcode)) {
			$qrcode = $this->generate($request);
			$res = ResultTool::success();
			return $res;
		} else {
			$res = ResultTool::fail();
			$res['errorMsg'] = "二维码已存在";
			return $res;
		}
	}

	private function generate($query)
	{
		$qrcode = new QrcodeModel();
		$qrcode->type = 'miniapp';
		$qrcode->mode = $query['mode'];
		$qrcode->page = $query['page'];
		$qrcode->name = $query['name'];
		$qrcode->createtime = date('Y-m-d H:i:s', time());
		if ($query['mode'] == 'table') {
			$qrcode->params = json_encode([
				'number' => $query['number']
			]);
		}
		$qrcode->save();

		$access_token = Common::getAccessToken();

		if ($query['mode'] == 'table') {
			$params = [
				'page' => $query['page'],
				'scene' => 'store_id=' . $query['store_id'] . '&qrcode_id=' . $qrcode->id
			];
		} else {
			$params = [
				'page' => $query['page'],
				'scene' => $query['scene']
			];
		}


		// 这里的参数需要使用raw的方式传参（！！！！这里需要注意）
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); // 必须为字符串
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain')); // 必须声明请求头
		// 如果没有错误的话返回的就是小程序码的文件流
		$result = curl_exec($ch);
		if (isset($result['errcode'])) { //查看文档错误代码
			$res = ResultTool::fail();
			$res['errorMsg'] = "获取小程序码出错";
			return $res;
		}

		// 服务器文件存储路径
		$img_path = (config('app.proj_identity') ? (config('app.proj_identity') . '/') : '') . "images/" . date('Y/m');
		$path = env('ATTACHMENT_ROOT') . $img_path;
		if (!is_dir($path)) {
			mkdir($path, 0777, true);
		}
		$filename = md5(date('ymdhis') . $query['scene']) . ".png";
		$filePath = $path . '/' . $filename; //最后要写入的目录及文件名
		//  创建将数据流文件写入我们创建的文件内容中
		$ifp = fopen($filePath, "w");
		fwrite($ifp, $result);
		fclose($ifp);

		$qrcode->scene = $params['scene'];
		$qrcode->qrcode = $img_path . '/' . $filename;
		$qrcode->save();
		return $qrcode;
	}

	public function delete(Request $request)
	{
		QrcodeModel::where('id', '=', $request->input('id'))->delete();
		return ResultTool::success();
	}
}
